<!-- 划转 -->
<template>
	<view>
		<HeaderBar :currentName="_t18('transfer')" @linkTo="-1"></HeaderBar>

		<view class="content_box">
			<p class="title fw-bold">{{ _t18('transfer') }}</p>

			<view class="cardOne">
				<view class="left">
					<!-- 从   到 -->
					<view class="left_top">
						<text>{{ _t18('transfer_from') }}</text>
						<van-dropdown-menu active-color="#17ac74">
							<van-dropdown-item v-model="params.transferOutAccount" :options="transferOutAccountList" />
						</van-dropdown-menu>
					</view>
					<view class="left_bottom">
						<text>{{ _t18('transfer_to', ['aams']) }}</text>
						<van-dropdown-menu active-color="#17ac74">
							<van-dropdown-item v-model="params.transferInAccount" :options="transferInAccountList" />
						</van-dropdown-menu>
					</view>
				</view>
				<view class="right" @click="jiaohuanbtn2">
					<svg-load name="huazhuanbtn" class="huazhuanbtn"></svg-load>
				</view>
			</view>
			<view class="cardTwo">
				<!-- 划转金额 -->
				<view class="top">{{ _t18('transfer_amount') }}</view>
				<view class="bottom">
					<input type="number"
						:placeholder="`${_t18('transfer_less', ['aams'])}1${params.coin?.toUpperCase() || 'USDT'}`"
						v-model="params.amount" @input="onAmountInput" @change="onAmountChange" @blur="onAmountBlur" />
					<span @click="amountAll">
						{{ _t18('swap_all') }}
					</span>
					<i>|</i>
					<van-dropdown-menu active-color="#17ac74">
						<van-dropdown-item v-model="symbolIndex" :options="assetsOptions" />
					</van-dropdown-menu>
				</view>
			</view>
			<!-- 可用余额 -->
			<view class="keyong">
				{{ _t18('transfer_available') }}：<span class="fw-num">{{ assetsList[symbolIndex]?.availableAmount || 0 }}
					{{ params.coin?.toUpperCase() || 'USDT' }}</span>
			</view>
			<view class="btnBox" @click="submit">
				<!-- 确认划转 -->
				<ButtonBar :btnValue="_t18('transfer_require')" :btnColor="'#138A5D'" />
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		DIFF_ISFREEZE
	} from '@/config/index'
	import {
		useFreeze
	} from '@/hook/useFreeze'
	import HeaderBar from "@/components/HeaderBar/index.vue"
	const {
		_isFreeze
	} = useFreeze()
	import ButtonBar from '@/components/common/ButtonBar/index.vue'
	import {
		getTransferList,
		getUserBalance
	} from '@/api/account'
	import {
		onMounted,
		ref,
		computed,
		watch
	} from 'vue'
	import {
		showToast
	} from 'vant'
	import {
		_t18
	} from '@/utils/public'
	import {
		useMainStore
	} from '@/store'
	import {
		useUserStore
	} from '@/store/user'

	const mainStore = useMainStore()
	const userStore = useUserStore()
	import {
		useToast
	} from '@/hook/useToast'
	const symbolIndex = ref(0)
	const {
		_toast
	} = useToast()
	const fromTxt = ref('')
	const toTxt = ref('')
	//数据
	const params = ref({
		coin: 'usdt',
		transferOutAccount: '',
		transferInAccount: '',
		amount: ''
	})
	// console.log(userStore.asset)



	//获取余额
	const availableList = ref([])
	const getBalance = async () => {
		let res = await getUserBalance()
		if (res.code == '200') {
			availableList.value = res.data
		}
	}
	// 计算余额   -->1 平台资产 2理财资产 3合约账户
	const availableAmount = computed(() => {
		console.log('计算可用余额 - symbolIndex:', symbolIndex.value, 'assetsList:', assetsList.value)
		console.log('计算可用余额 - params.coin:', params.value.coin, 'transferOutAccount:', params.value.transferOutAccount)
		
		// 从当前选中的资产获取可用余额
		if (assetsList.value && assetsList.value[symbolIndex.value]) {
			const selectedAsset = assetsList.value[symbolIndex.value]
			console.log('从选中资产获取余额:', selectedAsset.availableAmount)
			return selectedAsset.availableAmount || 0
		}
		
		// 如果没有选中资产，从 availableList 中查找对应币种的余额
		const currentCoin = params.value.coin
		if (currentCoin && availableList.value.length > 0) {
			const matchedItem = availableList.value.find(item => 
				item?.type == params.value.transferOutAccount && 
				item?.coin?.toLowerCase() === currentCoin.toLowerCase()
			)
			console.log('从 availableList 查找匹配项:', matchedItem)
			return matchedItem?.availableAmount || 0
		}
		
		console.log('没有找到匹配的余额，返回 0')
		return 0
	})
	// 监听下拉变化，同步币种
	watch(symbolIndex, (val) => {
		console.log('symbolIndex 变化:', val, 'assetsList:', assetsList.value)
		if (assetsList.value && assetsList.value[val]) {
			const selectedAsset = assetsList.value[val]
			if (selectedAsset.coin) {
				params.value.coin = selectedAsset.coin
				console.log('更新 params.coin 为:', params.value.coin, '来自资产:', selectedAsset)
			} else {
				console.warn('选中的资产没有 coin 字段:', selectedAsset)
			}
		} else {
			console.warn('assetsList 为空或索引超出范围')
		}
	})

	// 币种下拉选项
	const assetsOptions = computed(() => {
		return (assetsList.value || []).map((item, index) => ({
			text: item.symbol,
			value: index
		}))
	})

	// 选择器数据
	const tempList = computed(() => {
		const list = mainStore.getAssetsTabList.filter((item) => {
			// 对应参数key值 -->1 平台资产 2理财资产 3合约账户
			const key = {
				平台资产: 1,
				理财资产: 2,
				合约资产: 3,
				保本资产: 4
			}
			if (!item.isOpen) return false
			item.name == '平台资产' && (item.keyStr = _t18(item.keyStr, ['latcoin']))
			item.name == '理财资产' && (item.keyStr = _t18(item.keyStr, ['paxpay', 'latcoin']))
			item.name == '合约资产' && (item.keyStr = _t18(item.keyStr, ['paxpay', 'latcoin']))
			item.name == '保本资产' && (item.keyStr = _t18(item.keyStr, ['paxpay', 'latcoin']))

			item['text'] = item.keyStr
			item['value'] = key[item.name]
			return true
		})
		return list.sort((a, b) => a.sort - b.sort)
		// return list || []
	})
	//默认值
	params.value.transferOutAccount = tempList.value[0]?.value || ''
	params.value.transferInAccount = tempList.value[1]?.value || ''
	console.log("transferOutAccount:", params.value.transferOutAccount)
	const assetsList = computed(() => {
		const userAssets = userStore.asset || []
		console.log('userStore.asset:', userAssets)
		console.log('params.value.transferOutAccount:', params.value.transferOutAccount)
		const filtered = userAssets.filter(item => {
			return item.type == params.value.transferOutAccount
		})
		console.log('过滤后的 assetsList:', filtered)

		// 确保每个项目都有 symbol 和 coin 字段
		const processedList = filtered.map(item => ({
			...item,
			symbol: item.symbol || item.coin || 'USDT',
			coin: item.coin || item.symbol?.toLowerCase() || 'usdt'
		}))
		console.log('处理后的 assetsList:', processedList)

		// 如果没有数据，提供默认选项
		if (processedList.length === 0) {
			return [{
					symbol: 'USDT',
					coin: 'usdt',
					availableAmount: 0
				},
				{
					symbol: 'BTC',
					coin: 'btc',
					availableAmount: 0
				}
			]
		}

		return processedList
	})

	// 输入金额处理：正则清洗并不超过可用余额
	const onAmountInput = (e) => {
		console.log('input event:', e)
		console.log('e.detail:', e.detail)
		console.log('e.target:', e.target)
		console.log('e.currentTarget:', e.currentTarget)
		
		// 尝试不同的方式获取值
		let raw = ''
		if (e.detail && e.detail.value !== undefined) {
			raw = e.detail.value
		} else if (e.target && e.target.value !== undefined) {
			raw = e.target.value
		} else if (e.currentTarget && e.currentTarget.value !== undefined) {
			raw = e.currentTarget.value
		} else {
			// 如果都获取不到，使用当前 params.amount
			raw = String(params.value.amount || '')
		}
		
		console.log('raw value:', raw)
		
		// 仅保留数字和小数点
		raw = raw.replace(/[^\d.]/g, '')
		// 只保留第一个小数点
		raw = raw.replace(/\.(?=.*\.)/g, '')
		// 去除开头多余的0（保留类似0.xxx）
		raw = raw.replace(/^0+(?=\d)/, '0')
		// 规范形态：以点开头补0
		if (raw.startsWith('.')) raw = '0' + raw
		// 小数位按 8 位限制
		raw = raw.replace(/^(\d+)(\.(\d{0,8})?).*$/, (m, i, dot, frac) => (frac !== undefined ? i + '.' + (frac || '') : i))

		// 限制不超过可用余额
		const max = Number(availableAmount.value || 0)
		let num = Number(raw || 0)
		if (num > max) num = max

		params.value.amount = raw === '' ? '' : String(num)
	}

	// change 事件处理
	const onAmountChange = (e) => {
		console.log('change event:', e)
		console.log('change value:', e.detail?.value || e.target?.value)
		// 在 change 事件中再次处理
		onAmountInput(e)
	}

	// 失焦再次校验并规范格式
	const onAmountBlur = () => {
		let num = Number(params.value.amount || 0)
		const max = Number(availableAmount.value || 0)
		if (num > max) num = max
		// 去掉无意义的结尾小数0
		params.value.amount = num ? String(num) : ''
	}

	// 监听 params.amount 变化，实时校验
	watch(() => params.value.amount, (newVal) => {
		if (newVal && newVal !== '') {
			const max = Number(availableAmount.value || 0)
			const num = Number(newVal || 0)
			if (num > max) {
				params.value.amount = String(max)
			}
		}
	})

	// 监听 assetsList 变化，初始化 params.coin
	watch(assetsList, (newAssetsList) => {
		console.log('assetsList 变化:', newAssetsList, 'symbolIndex:', symbolIndex.value)
		if (newAssetsList && newAssetsList.length > 0) {
			// 确保 symbolIndex 在有效范围内
			if (symbolIndex.value >= newAssetsList.length) {
				symbolIndex.value = 0
			}
			
			// 设置 params.coin
			const selectedAsset = newAssetsList[symbolIndex.value]
			if (selectedAsset && selectedAsset.coin) {
				params.value.coin = selectedAsset.coin
				console.log('初始化 params.coin:', params.value.coin, '来自资产:', selectedAsset)
			} else {
				console.warn('选中的资产没有 coin 字段:', selectedAsset)
				// 使用默认值
				params.value.coin = 'usdt'
			}
		} else {
			console.warn('assetsList 为空，使用默认币种')
			params.value.coin = 'usdt'
		}
	}, {
		immediate: true
	})

	const transferOutAccountList = computed(() =>
		tempList.value.filter((item) => item.value != params.value.transferInAccount)
	)
	const transferInAccountList = computed(() =>
		tempList.value.filter((item) => item.value != params.value.transferOutAccount)
	)

	//提交
	const submit = () => {
		if (DIFF_ISFREEZE.includes(__config._APP_ENV)) {
			if (_isFreeze(DIFF_ISFREEZE)) {
				submitForm()
			}
		} else {
			submitForm()
		}
	}
	const submitForm = () => {
		console.log('提交参数:', params.value)
		console.log('当前币种:', params.value.coin)
		console.log('当前金额:', params.value.amount)
		
		if (params.value.amount == '' || params.value.amount <= 0) {
			// showToast('请输入划转金额')
			return _toast('transfer_please_amount')
		}

		// 金额不可大于可用余额
		if (Number(params.value.amount) > Number(availableAmount.value || 0)) {
			return _toast('transfer_amount_exceed')
		}

		getTransferList(params.value).then((res) => {
			if (res.code == '200') {
				// showToast('操作成功，请稍后...')
				_toast('transfer_success')
				getBalance()
			} else {
				showToast(res.msg || '')
			}
		})
	}

	const amountAll = () => {
		params.value.amount = availableAmount.value
	}

	//交换
	const jiaohuanbtn2 = () => {
		[params.value.transferOutAccount, params.value.transferInAccount] = [
			params.value.transferInAccount,
			params.value.transferOutAccount
		]
	}

	onMounted(() => {
		getBalance()
	})
</script>

<style lang="scss" scoped>
	* {
		font-size: 14px;
		color: var(--ex-default-font-color);
	}

	.picker-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 5px 10px;
		cursor: pointer;
		border: 1px solid #ddd;
		border-radius: 4px;
		background-color: #f9f9f9;

		&:hover {
			background-color: #f0f0f0;
		}
	}

	.picker-arrow {
		font-size: 12px;
		color: #666;
		margin-left: 5px;
	}

	.content_box {
		display: block;
		margin-top: 70px;
		padding: 0 15px;

		.title {
			display: block;
			font-size: 30px;
			margin: 30px 0;
		}

		.cardOne,
		.cardTwo {
			// display: block;
			padding: 0 20px;
			background-color: var(--ex-div-bgColor26);
			margin-top: 20px;
			border-radius: 5px;
		}

		.cardOne {
			display: flex;
			justify-content: space-between;
			align-items: center;

			// display: block;
			// padding:20px auto;
			.left {
				display: block;
				margin-right: 20px;
				flex: 1;

				&>view {
					padding: 15px 0;
					display: flex;
					color: var(--ex-font-color13);

					p {
						margin-left: 20px;
					}

					span {
						display: inline-block;
						width: 40px;
					}
				}

				.left_top {
					// display: block;
					border-bottom: 1px dashed var(--ex-border-color9);
					display: flex;
					align-items: center;
				}

				.left_bottom {
					// display: block;
					display: flex;
					align-items: center;
				}
			}

			.huazhuanbtn {
				display: block;
				font-size: 30px;
			}
		}

		.cardTwo {
			display: block;
			padding: 15px 15px;

			.top {
				display: block;
				margin-bottom: 15px;
				color: var(--ex-font-color13);
			}

			.bottom {

				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1px solid var(--ex-border-color8);

				i {
					padding: 0 10px;
				}

				span {
					color: var(--ex-font-color2);
				}

				input {
					flex: 1;
					margin-right: 20px;
					padding-bottom: 12px;

					background-color: transparent;
				}

				input::placeholder {
					color: var(--ex-font-color5);
				}
			}
		}

		.keyong {
			display: block;
			margin-top: 15px;
			color: var(--ex-font-color13);
			font-size: 12px;
		}

		.btnBox {
			display: block;
			margin-top: 50px;
		}
	}

	.van-dropdown-menu {
		flex: 1;
		display: flex;

		:deep(.van-popup--top) {
			max-width: var(--ex-max-width);
			left: 50%;
			translate: -50%;
		}
	}

	:deep(.van-cell) {
		background: var(--ex-default-background-color) !important;
		color: var(--ex-default-font-color);
	}

	:deep(.van-dropdown-menu__bar) {
		background-color: transparent;
		box-shadow: none;
		height: auto;
	}

	:deep(.van-dropdown-menu__title) {
		color: var(--ex-default-font-color);
		font-size: 14px;
		padding-left: 20px;
	}

	:deep(.van-dropdown-menu__title:after) {
		border-color: transparent transparent var(--ex-border-color9) var(--ex-border-color9);
	}
</style>